import * as zrender from "zrender";
import { barHeight, taskNamePaddingLeft, includeHoliday } from "../../config";
import { isHoliday } from "../../utils";

/**
 * 添加任务文字
 * @param {Object} group 任务组
 * @param {Object} task 任务对象
 * @param {number} width 宽度
 */
export function addTaskTexts(group: zrender.Group, task: Task, width: number) {
  // 任务名称
  const taskName = new zrender.Text({
    style: {
      text: task.name,
      x: taskNamePaddingLeft,
      y: barHeight / 2,
      stroke: "white",
      align: "left",
      verticalAlign: "middle",
      fill: "white"
    },
    cursor: 'move'
  });

  // 任务持续时间
  const taskDurationText = new zrender.Text({
    style: {
      text: `${getRealDuration(task, includeHoliday)}天`,
      x: width - taskNamePaddingLeft,
      y: barHeight / 2,
      stroke: "white",
      align: "left",
      verticalAlign: "middle",
      fill: "white"
    },
    cursor: 'move'
  });

  const { width: taskDurationTextWidth } = taskDurationText.getBoundingRect();
  taskDurationText.attr({
    style: {
      x: width - taskDurationTextWidth - taskNamePaddingLeft
    }
  });

  // 资源分配文字
  const resourceText = new zrender.Text({
    style: {
      text: "Assigned to: " + task.resource,
      x: 0 + width + 5,
      y: barHeight / 2 + 0 - 12 / 2,
      stroke: "black"
    },
    cursor: 'normal'
  });

  // 如果放不下，显示到resourceText上去，隐藏taskName
  if (taskName.getBoundingRect().width + taskDurationTextWidth + taskNamePaddingLeft * 2 > width) {
    resourceText.attr({
      style: {
        text: task.name
      }
    });
    taskName.hide();
  }

  group.add(taskName);
  group.add(taskDurationText);
  group.add(resourceText);
}


const taskStartDate = +new Date('2024-01-01')
const taskDayCount = 60 * 60 * 24 * 1000


// 获取天数
export function getRealDuration(task: Task, includeHoliday: boolean) {
  const { start, duration } = task;
  if (includeHoliday) return task.duration;
  let res = 0;
  const endLen = duration + start
  for (let i = start; i < endLen; i++) {
    if (isHoliday(new Date(taskStartDate + taskDayCount * i)).isHoliday) continue;
    res++;
  }
  return res
}
